const express=require('express');
const fs=require('fs');
const cors=require('cors')
const path=require("path");
const interfaces = require('os').networkInterfaces(); //本机地址
const TargetFilePath='./ip-collection.json'//输出文件地址
const {getCurrentFormatedTime}=require('./utils/index');//时间格式化生成工具
//获取地址
function getPath(val){
  return path.join(__dirname,val)
}
/**
 * promise形式的appendFile封装
 * @param {String} path 
 * @param {String} string 
 * @returns Promise
 */
const promiseAppendFile=(path,obj)=>{
  return new Promise((resolve,reject)=>{
    fs.readFile(TargetFilePath,(err,data)=>{
      let str=data.toString('utf-8');
      let arr=str?JSON.parse(str):[];
      // console.log(obj)
      //已存在ip与端口号全部相同的情况下直接删除原数据
      arr=arr.filter(v=>v.nickname!=obj.nickname);
      arr.push(obj);
      str=JSON.stringify(arr);
      fs.writeFile(path,str,(err)=>{
        if(err)reject(err);
        else resolve(1);
      })

    })
    
  })
}

let IPAdress = '';
const IPv4Prefix='::ffff:';
//遍历获取本机ip
for(let devName in interfaces){
    const iface = interfaces[devName];
    for(let i=0;i<iface.length;i++){
        let alias = iface[i];
        if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
            IPAdress = alias.address;
        }
    }
}
//不存在的情况下增加json文件
try {
  fs.statSync(TargetFilePath)
} catch {
  fs.writeFile(TargetFilePath,'',err=>{
    console.log(err);
  })
}
const app=express();
app.use('/list',express.static(getPath('./pages')));
app.use(cors());
app.get('/get-list',(req,res)=>{
  fs.readFile(TargetFilePath,(err,data)=>{
    data=data.toString('utf-8');
    res.send({code:200,data});
  })
})
//处理请求
app.get('/',(req,res)=>{
  let time=getCurrentFormatedTime();
  const nickname=req.query.name||'匿名';
  const port=req.query.port ||'9100';
  const isBack=req.query.isBack;
  let newIp=req.ip;
  newIp=req.ip.replace(IPv4Prefix,'');
  let obj={
    apiName:'apiRoot',
    newIp:'http://'+newIp,
    isBack:typeof isBack !='undefined'?isBack:1,
    port,
    nickname,
    time
  }
  // let str=`\t //let apiRoot = "http://${newIp}:${port}/";// ${nickname}  -- ${time}\n
  // `;
  promiseAppendFile(TargetFilePath,obj).then(()=>{
    res.send({code:200,data:obj})
  }).catch(()=>{
    res.send({code:201,msg:'[配置文件添加失败]',data:obj})
  })
  })
app.listen('8888',()=>{
  console.log(`Server running at http://${IPAdress}:8888/list`);
})